module.exports = {
    
    /**
     * 新增一条明细
     */
    saveDetail: async function ({ cashbookId, userId, type, amt, remark, picUrl, userAvatar, amtType, creatDate }) {
        let sql = 'insert into detail'
        sql += ' (cashbook_id, user_id, type, amt, create_time, remark, pic_url, user_avatar, amt_type, create_date)'
        sql += ' values (?, ?, ?, ?, now(), ?, ?, ?, ?, ?)'
        const result = await dbexec(sql, [cashbookId, userId, type, amt, remark, picUrl, userAvatar, amtType, creatDate])
        return result
    },

    /**
     * 查询一个账本明细
     */
    getDetailList: async function ({ cashbookId, year, month }) {
        if (!year) {
            year = new Date().getFullYear()
        }

        if (!month) {
            month = new Date().getMonth() + 1
        }

        let sql = 'SELECT * FROM detail'
        sql += ` where cashbook_id = ${cashbookId}`
        sql += ` and create_date >= '${year}-${month}-01' and create_date < '${year}-${Number(month) + 1}-01'`
        sql += ' order by create_time desc'

        const result = await dbexec(sql)
        return result
    },

    /**
     * 查询一条明细
     */
    getDetail: async function ({ id }) {
        const sql = `SELECT * FROM detail where id = ${id}`
        const result = await dbexec(sql)
        return result
        
    },

    /**
     * 删除一条明细
     */
    deleteDetail: async function ({ id }) {
        const sql = `delete FROM detail where id = ${id}`
        const result = await dbexec(sql)
        return result
    },

    /**
     * 修改一条明细
     */ 
    updateDetail: async function ({ amt, remark, picUrl, type, id }) {
        let sql = 'update detail set last_update_time = now()'   
        if (amt) {
            sql += `, amt = ${amt} `
        }
        if (remark) {
            sql += `, remark = "${remark}" `
        }
        if (picUrl) {
            sql += `, pic_url = "${picUrl}" `
        }
        if (type) {
            sql += `, type = "${type}" `
        }
        sql += `where id = ${id}`
        const result = await dbexec(sql)
        return result
    },

}